package com.shoulder.boot.system.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shoulder.boot.system.dto.LogQueryDTO;
import com.shoulder.boot.system.entity.Tenant;
import com.shoulder.boot.system.mapper.LogMapper;
import com.shoulder.boot.system.mapper.TenantMapper;
import com.shoulder.boot.system.service.LogService;
import com.shoulder.boot.system.vo.LogVo;
import com.shoulder.boot.system.utils.LogUtils;
import com.shoulder.log.Log;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.util.List;
import java.util.stream.Collectors;

@AllArgsConstructor
@Service
@Transactional
public class LogServiceImpl extends ServiceImpl<LogMapper, Log> implements LogService {
    private final TenantMapper tenantMapper;
    ;

    @Override
    public Page<LogVo> pageQuery(LogQueryDTO queryDTO) {
        Page<Log> selectPage = this.baseMapper.selectPage(new Page<>(queryDTO.getCurrent(), queryDTO.getSize())
                , buildQueryWrapper(queryDTO));
        if (selectPage != null && !CollectionUtils.isEmpty(selectPage.getRecords())) {
            return LogUtils.buildUtils(selectPage.getRecords(), tenantMapper).toPage(selectPage);
        }
        return new Page<>();
    }

    private LambdaQueryWrapper<Log> buildQueryWrapper(LogQueryDTO queryDTO) {
        LambdaQueryWrapper<Log> queryWrapper = new LambdaQueryWrapper<Log>().orderByDesc(Log::getCreateTime);
        queryWrapper.like(!ObjectUtils.isEmpty(queryDTO.getTitle()), Log::getTitle, queryDTO.getTitle());
        queryWrapper.like(!ObjectUtils.isEmpty(queryDTO.getDeviceType()), Log::getDeviceType, queryDTO.getDeviceType());
        queryWrapper.like(!ObjectUtils.isEmpty(queryDTO.getNickname()), Log::getNickname, queryDTO.getNickname());

        return queryWrapper;
    }
}
